package com.mtiiot.fstcpserver.fastdfs;

import com.mtiiot.fstcpserver.fastdfs.core.*;
import com.mtiiot.fstcpserver.fastdfs.core.*;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool.Config;

import java.net.InetSocketAddress;

/**
 * Created by lcy on 16-6-28.
 */
public class FastdfsDataSource {
    protected String trackerServers;//多个用逗号隔开  eg:10.117.215.193:22122,10.117.206.248:22123
    protected int connectTimeout;
    protected int networkTimeout;
    protected String charset;
    protected int httpTrackerHttpPort;
    protected boolean httpAntiStealToken;
    protected String httpSecretKey;

    protected int maxActive;
    protected int maxIdle;
    protected int minIdle;
    protected long maxWait;

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public int getNetworkTimeout() {
        return networkTimeout;
    }

    public void setNetworkTimeout(int networkTimeout) {
        this.networkTimeout = networkTimeout;
    }

    public String getTrackerServers() {
        return trackerServers;
    }

    public void setTrackerServers(String trackerServers) {
        this.trackerServers = trackerServers;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public int getHttpTrackerHttpPort() {
        return httpTrackerHttpPort;
    }

    public void setHttpTrackerHttpPort(int httpTrackerHttpPort) {
        this.httpTrackerHttpPort = httpTrackerHttpPort;
    }

    public boolean getHttpAntiStealToken() {
        return httpAntiStealToken;
    }

    public void setHttpAntiStealToken(boolean httpAntiStealToken) {
        this.httpAntiStealToken = httpAntiStealToken;
    }

    public String getHttpSecretKey() {
        return httpSecretKey;
    }

    public void setHttpSecretKey(String httpSecretKey) {
        this.httpSecretKey = httpSecretKey;
    }

    public int getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public int getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public int getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }


    public long getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(long maxWait) {
        this.maxWait = maxWait;
    }

    private GenericObjectPool pool;
    public FastdfsDataSource(){
    }

    public void initPool()throws Exception{
        Config config=new Config();
        config.maxActive=this.maxActive;
        config.maxIdle=maxIdle;
        config.minIdle=minIdle;
        config.maxWait=maxWait;

        String[] trs=trackerServers.split(",");
        InetSocketAddress[] trackerServers = new InetSocketAddress[trs.length];
        int i=0;
        for(String tr:trs){
            String[] strTmps=tr.split(":");
            trackerServers[i]=new InetSocketAddress(strTmps[0],Integer.parseInt(strTmps[1]));
            i++;
        }
        ClientGlobal.setG_tracker_group(new TrackerGroup(trackerServers));
        // 连接超时的时限，单位为毫秒 
        ClientGlobal.setG_connect_timeout(connectTimeout);// 网络超时的时限，单位为毫秒 
        ClientGlobal.setG_network_timeout(networkTimeout);
        ClientGlobal.setG_anti_steal_token(httpAntiStealToken);// 字符集 
        ClientGlobal.setG_charset(charset);
        ClientGlobal.setG_tracker_http_port(httpTrackerHttpPort);
        ClientGlobal.setG_secret_key(httpSecretKey);

        ConnectionFactory factory = new ConnectionFactory();
        pool = new GenericObjectPool(factory, config);
    }

    public StorageClient1 getConnection() throws Exception{
        if(pool==null){
            initPool();
        }
        return (StorageClient1)pool.borrowObject();
    }

    public void releaseConnection(StorageClient1 storageClient1)throws Exception{
        if(pool==null){
            initPool();
        }
        pool.returnObject(storageClient1);
    }

    /**
     * inner
     * @author qing
     *
     */
    class ConnectionFactory extends BasePoolableObjectFactory {
        public ConnectionFactory(){
        }
        @Override
        public Object makeObject() throws Exception {
            TrackerServer trackerServer = null;
            TrackerClient trackerClient = new TrackerClient();//Only tracker 
            trackerServer = trackerClient.getConnection();
            StorageServer storageServer=null;
            StorageClient1 client1=new StorageClient1(trackerServer,storageServer);
            return client1;
        }

        public void destroyObject(Object obj) throws Exception  {
            if(obj instanceof StorageClient1){
                StorageClient1 client1=(StorageClient1)obj;
                TrackerServer trackerServer=client1.getTrackerServer();
                StorageServer storageServer=client1.getStorageServer();
                if(trackerServer!=null){
                    trackerServer.close();
                }
                if(storageServer!=null){
                    storageServer.close();
                }
            }
        }

//        public boolean validateObject(Object obj) {
//            if(obj instanceof StorageClient1){
//                StorageClient1 socket = ((StorageClient1)obj);
//                if(!socket.isConnected()){
//                    return false;
//                }
//                if(socket.isClosed()){
//                    return false;
//                }
//                return true;
//            }
//            return false;
//        }
    }

}
